package handler

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/share309/gojwt"
	"net/http"
	"shop/api/requset"
	"shop/consts"
	"shop/internal/dao"
	"shop/internal/model"
	"time"
)

// 注册
func Register(c *gin.Context) {
	//接收参数
	var req requset.RegisterReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}

	//业务逻辑
	//1.验证账号唯一
	var user model.User
	dao.GetOneByFields(&model.User{Mobile: req.Mobile}, &user)
	if user.Id > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "账号已存在",
			"data": nil,
		})
		return
	}

	//2.注册
	result := dao.Create(&model.User{
		Mobile:   req.Mobile,
		Password: req.Password,
	})
	if !result {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "注册失败",
			"data": false,
		})
		return
	}

	//返回参数
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "注册成功",
		"data": true,
	})
	return
}

// 登录
func Login(c *gin.Context) {
	//接收参数
	var req requset.LoginReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": err.Error(),
		})
		return
	}

	//业务逻辑
	//1.验证用户
	var user model.User
	dao.GetOneByFields(&model.User{
		Mobile:   req.Mobile,
		Password: req.Password,
	}, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "账号密码错误",
			"data": nil,
		})
		return
	}

	//2.生产token
	token, err := gojwt.NewJWT(consts.JWT_KEY).CreateToken(gojwt.CustomClaims{
		ID: user.Id,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() * 86400 * 1, //1天有效期
		},
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "token生成失败",
			"data": nil,
		})
		return
	}

	//返回参数
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "登录成功",
		"data": token,
	})
	return

}
